package com.gitee.zeric.codec.generaters;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.gitee.zeric.codec.exception.ParamErrorException;
import com.gitee.zeric.codec.util.VUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;

/**
 * 字母生成器
 *
 * @author zj
 * @date 2021/12/15
 */
@Slf4j
public class LetterGenerater extends AbstractCodeGerator {
    @Override
    public String generate(String ruleCode,JSONObject param)  {
        RuleParam ruleParam = trans(RuleParam.class, param);
        if (ruleParam.getUpperCase() ==2) {
            return RandomUtil.randomString("abcdefghigklmnopqrstuvwxyz" +
                    "ABCDEFGHIJKLMNOPQRSTUVWXYZ", ruleParam.getSize());
        }
        //最终生成的字符串
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < ruleParam.getSize(); i++) {
            str.append((char) (Math.random() * 26 + (ruleParam.getUpperCase()==0 ? 'A' : 'a')));
        }
        return str.toString();
    }

    @Override
    protected String[] fields() {
        return new String[]{"size","upperCase"};
    }

    @Override
    public void checkParam(JSONObject paramJson) {
        super.checkParam(paramJson);
        RuleParam ruleParam = trans(RuleParam.class, paramJson);
        try {
            Integer upperCase = ruleParam.getUpperCase();
            VUtils.isTure(!Arrays.asList(0,1,2).contains(upperCase)).throwMessage("请检查字母大小写参数！");
        } catch (Exception e) {
            throw new ParamErrorException("请检查upperCase字段值类型是否为数字！");
        }
    }
}
